package com.duff.download.demo;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.duff.download.okdownload.AbsDownloadManager;
import com.duff.download.okdownload.DownloadError;
import com.duff.download.okdownload.DownloadManager;
import com.duff.download.okdownload.DownloadObserver;
import com.duff.download.okdownload.DownloadStatus;
import com.duff.download.okdownload.model.DownloadInfo;
import com.duff.download.okdownload.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: duff
 * Date: 2017/10/31
 * Version: 1.0.0
 * Description:
 */

public class ListDownloadActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {

    private static final String TAG = "ListDownloadActivity";

    private Button bt_download, bt_pause, bt_resume, bt_clear;
    private ListView mListView;

    private String DOWNLOAD_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/aaa/";

    private List<DownloadInfo> mDownloadInfos = new ArrayList<>();
    private DownloadAdapter mAdapter;

    private final String[] urls = new String[]{
            "http://f3.market.xiaomi.com/download/AppStore/08c674eee0f857ed80f0efa9158a6cb021c42957b/com.imibaby.client.apk",
//            "http://f4.market.mi-img.com/download/AppStore/090485ebaf2f57463cb7ad073bafce391f3410ee7/com.tencent.tmgp.xxsy.apk",
            "http://f5.market.mi-img.com/download/AppStore/01a8e414d25119552da45e79abcc8f31ec740b7dd/com.qiyi.video.apk",
//            "http://f5.market.mi-img.com/download/AppStore/014c9f45c21e04872011945709d58888d702bab94/cn.ecook.apk",
//            "http://f4.market.mi-img.com/download/AppStore/082b859d865573fb1844d0a38a8d09b99a4427274/com.migao.overseasstudy.apk",
            "http://f2.market.xiaomi.com/download/AppStore/032e015d0d3cf43270d908c3635ed3321020daaea/cn.edu.zjicm.listen.apk",
            "http://imgsrc.baidu.com/image/c0%3Dshijue1%2C0%2C0%2C294%2C40/sign=9909ddc1b91c8701c2bbbaa54f16f45a/a08b87d6277f9e2fb0727e2d1530e924b899f354.jpg",
            "http://imgsrc.baidu.com/image/c0%3Dshijue1%2C0%2C0%2C294%2C40/sign=ae4e87268d94a4c21e2eef68669d71a0/7c1ed21b0ef41bd5d5a88edd5bda81cb39db3d1b.jpg"
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_download);

        bt_download = (Button) findViewById(R.id.bt_download);
        bt_download.setOnClickListener(this);
        bt_pause = (Button) findViewById(R.id.bt_pause);
        bt_pause.setOnClickListener(this);
        bt_resume = (Button) findViewById(R.id.bt_resume);
        bt_resume.setOnClickListener(this);
        bt_clear = (Button) findViewById(R.id.bt_clear);
        bt_clear.setOnClickListener(this);

        mListView = (ListView) findViewById(R.id.listView);
        mListView.setOnItemClickListener(this);
        mListView.setOnItemLongClickListener(this);

        mAdapter = new DownloadAdapter(this, mDownloadInfos);
        mListView.setAdapter(mAdapter);
        getDownloadList();

        DownloadManager.instance(this).setMaxRunningTask(3); // 最大任务建议设置为1
        DownloadManager.instance(this).registerDownloadObserver(mDownloadObserver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DownloadManager.instance(this).unRegisterDownloadObserver(mDownloadObserver);
    }

    private void getDownloadList() {
        DownloadManager.instance(this).queryAll(new AbsDownloadManager.QueryCallback<DownloadInfo>() {
            @Override
            public boolean onQueryFinished(int errorCode, DownloadInfo[] items) {
                if (items != null) {
                    for (DownloadInfo item : items) {
                        mDownloadInfos.add(item);
                    }
                    mAdapter.notifyDataSetChanged();
                }
                return true;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_download:
                download();
                break;

            case R.id.bt_pause:
                pauseAll();
                break;

            case R.id.bt_resume:
                resumeAll();
                break;

            case R.id.bt_clear:
                clearData();
                break;

            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        DownloadInfo info = mAdapter.getItem(position);
        int status = info.getStatus();
        if (status == DownloadStatus.STATUS_STARTED || status == DownloadStatus.STATUS_PENDED) {
            DownloadManager.instance(ListDownloadActivity.this).pause(info.getId());
        } else if (status != DownloadStatus.STATUS_DOWNLOAD_COMPLETED) {
            DownloadManager.instance(ListDownloadActivity.this).resume(info.getId());
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setItems(new String[]{"删除"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                DownloadInfo info = mDownloadInfos.get(position);
                DownloadManager.instance(ListDownloadActivity.this).delete(false, info.getId(), new AbsDownloadManager.DeleteCallback<DownloadInfo>() {
                    @Override
                    public boolean onDeleteFinished(int errorCode, DownloadInfo[] items) {
                        if (errorCode == DownloadError.ERROR_SUCCESS) {
                            mDownloadInfos.remove(position);
                            mAdapter.notifyDataSetChanged();
                            Toast.makeText(ListDownloadActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                        }

                        return true;
                    }
                });
            }
        });
        builder.show();
        return true;
    }

    private void download() {
        DownloadInfo[] downloadInfos = new DownloadInfo[urls.length];
        for (int i = 0; i < urls.length; i++) {
            DownloadInfo info = new DownloadInfo();

            String url = urls[i];
            String fileName = Utils.getFileName(url);
            String filePath = DOWNLOAD_DIR + fileName;

            info.setUrl(urls[i]);
            info.setTag(fileName);
            info.setPath(filePath);
            info.setTaskName(fileName);

            downloadInfos[i] = info;
        }

        DownloadManager.instance(this).add(callback, downloadInfos);
    }

    private void pauseAll() {
        DownloadManager.instance(this).pauseAll();
    }

    private void resumeAll() {
        DownloadManager.instance(this).resumeAll();
    }

    private void clearData() {
        DownloadManager.instance(this).deleteAll(new AbsDownloadManager.DeleteCallback<DownloadInfo>() {
            @Override
            public boolean onDeleteFinished(int errorCode, DownloadInfo[] items) {
                if (errorCode == DownloadError.ERROR_SUCCESS) {
                    mDownloadInfos.clear();
                    mAdapter.notifyDataSetChanged();
                    Toast.makeText(ListDownloadActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                }

                return true;
            }
        });
    }

    private AbsDownloadManager.AddCallback<DownloadInfo> callback = new AbsDownloadManager.AddCallback<DownloadInfo>() {
        @Override
        public boolean onAddFinished(int errorCode, DownloadInfo[] items) {
            Log.d(TAG, "onAddFinished errorCode:" + errorCode);
            handleErrorCode(errorCode, items);

            return true;
        }
    };

    private void handleErrorCode(int errorCode, DownloadInfo[] downloadInfos) {
        String msg = "";
        switch (errorCode) {
            case DownloadError.ERROR_SUCCESS:
                for (DownloadInfo info : downloadInfos) {
                    mDownloadInfos.add(info);
                }
                mAdapter.notifyDataSetChanged();
                break;

            case DownloadError.ERROR_NETWORK:
                msg = "网络错误";
                break;

            case DownloadError.ERROR_SDCARD_INVALID:
                msg = "SDCard不可用";
                break;

            case DownloadError.ERROR_SDCARD_FULL:
                msg = "SDCard已满";
                break;

            case DownloadError.ERROR_INVALID_URL:
                msg = "Url不合法";
                break;

            case DownloadError.ERROR_DUPLICATE_DOWNLOAD:
                msg = "重复下载";
                break;

            default:
                msg = "其他错误，错误码：" + errorCode;
                break;
        }
        if (!TextUtils.isEmpty(msg)) {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }
    }

    private DownloadObserver mDownloadObserver = new DownloadObserver() {
        @Override
        public void onUpdateStatus(DownloadInfo downloadInfo) {
            Log.d(TAG, "onUpdateStatus----" + " taskId:" + downloadInfo.getTag() + "  status:" + downloadInfo.getStatus());
            for (DownloadInfo info : mDownloadInfos) {
                if (info.getId() == downloadInfo.getId()) {
                    info.setDownloadedBytes(downloadInfo.getDownloadedBytes());
                    info.setTotalSize(downloadInfo.getTotalSize());
                    info.setStatus(downloadInfo.getStatus());
                    info.setErrorCode(downloadInfo.getErrorCode());
                    break;
                }
            }
            mAdapter.notifyDataSetChanged();
        }

        @Override
        public void onProgress(DownloadInfo downloadInfo) {
            Log.d(TAG, "onProgress:" + downloadInfo.getDownloadedBytes() + "/" + downloadInfo.getTotalSize());
            for (DownloadInfo info : mDownloadInfos) {
                if (info.getId() == downloadInfo.getId()) {
                    info.setDownloadedBytes(downloadInfo.getDownloadedBytes());
                    info.setTotalSize(downloadInfo.getTotalSize());
                    info.setStatus(downloadInfo.getStatus());
                    info.setErrorCode(downloadInfo.getErrorCode());
                    break;
                }
            }
            mAdapter.notifyDataSetChanged();
        }
    };

}
